package com.typing.battle.receiver;


import java.io.IOException;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;

import android.app.PendingIntent.CanceledException;
import android.content.BroadcastReceiver;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.os.Vibrator;
import android.util.Log;
import android.view.Gravity;
import android.widget.Toast;

import com.typing.battle.R;
import com.typing.battle.activity.TypingBattleChatRoomActivity;
import com.typing.battle.util.PreferenceMgr;
import com.typing.battle.util.ServerComunicationUtil;
import com.typing.battle.value.MessageDTO;
import com.typing.battle.value.ServerComunicationDTO;

public class ServerPollingReceiver extends BroadcastReceiver {

	static String registration_id = null;
	public static TypingBattleChatRoomActivity chatRoomActivity;
	public static final int TYPE_MESSAGE = 0;
	public static final int TYPE_NOTIFY = 1;
	public static final int TYPE_INVITE = 2;
	public static final int TYPE_ROOM_IN = 3;
	public static final int TYPE_ROOM_OUT = 4;
	public static final int TYPE_ROOM_BANISH = 5;	
	public static final int TYPE_TYPING_START = 6;
	public static final int TYPE_TYPING_END = 7;
	public static final int TYPE_TYPING_RESULT = 8;	
	
	private PreferenceMgr mgr;
	@Override
	public void onReceive(Context context, Intent intent) {
		if (intent.getAction().equals(
				"com.typing.battle.polling.RECEIVE")) {
			chatRoomActivity = TypingBattleChatRoomActivity.typingBattleActivity;
			mgr = PreferenceMgr.getInstance(context);
			int type = Integer.parseInt(intent.getExtras().getString("sendType"));
			String c2dm_msg = intent.getExtras().getString("msg");
			String msg_from = intent.getExtras().getString("msg_from");
			String msg_from_name = intent.getExtras().getString("msg_from_name");
			MessageDTO dto = new MessageDTO(type,c2dm_msg,msg_from,msg_from_name);
			Log.d("msg",c2dm_msg);
			Log.d("msg_from",msg_from);
			Log.d("msg_from_name",msg_from_name);
			Log.d("type",""+type);
			Toast toast = null;
			Log.d("", "onReceive Type ====>>>"+type);
			
			switch(type){
			case TYPE_MESSAGE :	
				Log.d("chatRoomActivity",""+chatRoomActivity);
				if(!mgr.getData(PreferenceMgr.USER_EMAIL_KEY, "").equals(msg_from)){
					chatRoomActivity.setReceiveMessage(dto);
				}
				/*
					Toast toast = Toast.makeText(context, "메시지 도착!\n" + c2dm_msg,
							Toast.LENGTH_SHORT);
					toast.setGravity(Gravity.TOP | Gravity.CENTER, 0, 150);
					toast.show();
					
					//TypingBattleChatRoomActivity.chatView.list.add(new String[]{msg_from,c2dm_msg,"right"});
					//TypingBattleChatRoomActivity.chatView.refreshData();
					break;
				}else{
					
				}*/		
				break;
			case TYPE_NOTIFY :
					break;
			case TYPE_INVITE :
				Intent contentIntent = new Intent(context,TypingBattleChatRoomActivity.class);
				contentIntent.putExtra("CHAT_ROOM_ID", c2dm_msg);
				contentIntent.putExtra("isInvite", true);
				PendingIntent appIntent = PendingIntent.getActivity(context, 0, contentIntent, PendingIntent.FLAG_UPDATE_CURRENT);
				CharSequence from = "Typing battle";
				CharSequence message = msg_from +"님께서 초대하였습니다.";
				
				Notification notice = new Notification(R.drawable.icon,null,System.currentTimeMillis());
				//notice.sound = Uri.withAppendedPath(Audio.Media.INTERNAL_CONTENT_URI, "6");
				notice.flags = Notification.FLAG_INSISTENT;
				notice.setLatestEventInfo(context, from, message, appIntent);
				notice.ledARGB = Color.GREEN;		
				NotificationManager nm = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
				nm.notify(1234,notice);
				Vibrator vibrator = (Vibrator)context.getSystemService(Context.VIBRATOR_SERVICE);
			    vibrator.vibrate(300);
			    PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
			    WakeLock wl = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK|PowerManager.ACQUIRE_CAUSES_WAKEUP, "invite wake up");
			    wl.acquire(5000);
			    toast = Toast.makeText(context, msg_from +"님께서 초대하였습니다.",
						Toast.LENGTH_SHORT);
				toast.setGravity(Gravity.TOP | Gravity.CENTER, 0, 150);
				toast.show();
					break;
			case TYPE_ROOM_IN :
				if(!mgr.getData(PreferenceMgr.USER_EMAIL_KEY, "").equals(msg_from)){
					dto.setMsg(c2dm_msg + "님이 입장 하셨습니다.");
					chatRoomActivity.setReceiveMessage(dto);
				}else{
					//toast = Toast.makeText(context, "채팅방에 입장하였습니다.",
					//		Toast.LENGTH_SHORT);
					//toast.setGravity(Gravity.TOP | Gravity.CENTER, 0, 150);
					//toast.show();
				}
				
					break;		
			case TYPE_ROOM_OUT :
				if(!mgr.getData(PreferenceMgr.USER_EMAIL_KEY, "").equals(msg_from)){
					dto.setMsg(c2dm_msg + "님이 퇴장 하셨습니다.");
					chatRoomActivity.setReceiveMessage(dto);
				}else{
					//toast = Toast.makeText(context, "채팅방에서 나오셨습니다.",
					//		Toast.LENGTH_SHORT);
					//toast.setGravity(Gravity.TOP | Gravity.CENTER, 0, 150);
					//toast.show();
				}
				
					break;
			case TYPE_ROOM_BANISH :
				
				if(mgr.getData(PreferenceMgr.USER_EMAIL_KEY, "").equals(c2dm_msg)){
					//chatRoomActivity.exitRoom();
					toast = Toast.makeText(context, "방에서 강제 추방되었습니다.",
							Toast.LENGTH_SHORT);
					toast.setGravity(Gravity.TOP | Gravity.CENTER, 0, 150);
					toast.show();
					chatRoomActivity.finish();
				}else{
					dto.setMsg(c2dm_msg + "님이 추방되었습니다.");
					chatRoomActivity.setReceiveMessage(dto);
				}
				
				break;
			case TYPE_TYPING_START :
					toast = Toast.makeText(context, "타이핑시작",
							Toast.LENGTH_SHORT);
					toast.setGravity(Gravity.TOP | Gravity.CENTER, 0, 150);
					toast.show();					
					dto.setMsg(intent.getExtras().getString("sentence"));
					chatRoomActivity.setReceiveMessage(dto);
					chatRoomActivity.startTyping(intent.getExtras().getString("sentence"),intent.getExtras().getString("sentenceId"),intent.getExtras().getString("seq"));
					Log.d("sentenceID" , ""+intent.getExtras().getString("sentenceId"));
					break;
			case TYPE_TYPING_END :					
					chatRoomActivity.endTyping();
					break;
			case TYPE_TYPING_RESULT :
					toast = Toast.makeText(context, "타이핑종료",
							Toast.LENGTH_SHORT);
					toast.setGravity(Gravity.TOP | Gravity.CENTER, 0, 150);
					toast.show();
					chatRoomActivity.setReceiveMessage(dto);
					chatRoomActivity.endTyping();
					break;
			}
			
		}
	}

	private void handleRegistration(Context context, Intent intent) {
		registration_id = intent.getStringExtra("registration_id");
		System.out.println("registration_id====>" + registration_id);
		System.out.println("ERROR====>" + intent.getStringExtra("error"));
		if (intent.getStringExtra("error") != null) {
			Log.d("C2DM_REGISTRATION", ">>>>>"
					+ "Registration failed, should try again later." + "<<<<<");
		} else if (intent.getStringExtra("unregistered") != null) {
			Log.d("C2DM_REGISTRATION",
					">>>>>"
							+ "unregistration done, new messages from the authorized sender will be rejected"
							+ "<<<<<");
		} else if (registration_id != null) {
			System.out.println("registration_id complete!!");
			PreferenceMgr mgr = PreferenceMgr.getInstance(context);
			mgr.setData(PreferenceMgr.REGISTRATION_KEY, registration_id);
		}
	}

}